package com.hankol.newretail.adapter

import android.graphics.Paint
import android.util.Log
import android.view.View
import android.view.View.OnAttachStateChangeListener
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import cn.iwgang.countdownview.CountdownView
import com.baselibrary.Constants
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.ProgressWithTextBar
import com.baselibrary.view.RoundCornerImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.hankol.newretail.R
import com.hankol.newretail.adapter.details.GoodsDetailAdapter
import com.hankol.newretail.bean.SeckillCategoryActList
import java.util.HashMap


/**
 *@author:hanke
 *2022/3/30
 *desc:
 */
class SeckillAdapter(var layoutId: Int, var datas: ArrayList<SeckillCategoryActList>) : BaseQuickAdapter<SeckillCategoryActList, BaseViewHolder>(layoutId, datas) {
    private var clickButtonListener: GoodsDetailAdapter.ClickButtonListener? = null
    fun setClickButtonListener(clickButtonListener: GoodsDetailAdapter.ClickButtonListener) {
        this.clickButtonListener = clickButtonListener
    }

    private var showType = "1"
    fun setShowType(showType: String) {
        this.showType = showType
    }

    override fun convert(helper: BaseViewHolder, item: SeckillCategoryActList) {
        helper.getView<TextView>(R.id.tv_good_price).paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        val longCover = helper.getView<RoundCornerImageView>(R.id.iv_goods_cover)
        if (showType == "0") {
            val p: ViewGroup.LayoutParams = longCover.layoutParams
            p.height = ((ScreenUtils.getVideoHight(item.spuIconLong).toFloat() / ScreenUtils.getVideoWidth(item.spuIconLong).toInt()) * (ScreenUtils.getScreenWidth() - ScreenUtils.dpToPx(28))).toInt()
            longCover.layoutParams = p
        }
        if (item.spuIcon.checkValue().checkNotNull()) {
            longCover.load(mContext, if (showType == "0") item.spuIconLong.checkValue() else item.spuIcon.checkValue())
        }
        helper.setText(R.id.tv_goods_name, item.spuName)
        helper.setGone(R.id.iv_play_button, item.hasVideos == 1)
        val progress = helper.getView<ProgressWithTextBar>(R.id.pg_percent)
        progress.setProgressColor(ContextCompat.getColor(mContext, R.color.color_D53))
        progress.setBgColor(ContextCompat.getColor(mContext, R.color.color_D53_a30))
        progress.setTextColor(ContextCompat.getColor(mContext, R.color.white))
        progress.setTextSize(8f)
        //向下取整
        val progressStr = Math.floor(item.seckillActProductExtDTO?.sales?.div(item.seckillActProductExtDTO.stock?.toFloat()!!)?.times(100)?.toDouble()!!)
        progress.setText("${CommonUtil.formatNum(progressStr.toFloat()).toInt()}")
        val progressValue = item.seckillActProductExtDTO?.sales?.div(item.seckillActProductExtDTO.stock?.toFloat()!!)
//        HKLogUtils.e("进度值：${progressValue}")
        progress.setProgressWithAnimation(progressValue!!)
        progress.addOnAttachStateChangeListener(object :OnAttachStateChangeListener{
            override fun onViewAttachedToWindow(v: View?) {
                progress.setProgressWithAnimation(progressValue!!)
            }

            override fun onViewDetachedFromWindow(v: View?) {
            }
        })
        val startTime = item.seckillActProductExtDTO!!.stime
        val endTime = item.seckillActProductExtDTO?.etime
        val timer = helper.getView<CountdownView>(R.id.tv_seckill_left_time)
        val button = helper.getView<TextView>(R.id.tv_subscribe_status)
        if (System.currentTimeMillis() < startTime) {
            progress.visibility = View.GONE
            timer.customTimeShow(startTime - System.currentTimeMillis() >= 1000 * 60 * 60 * 24, true, true, true, false)
            helper.setText(R.id.tv_seckill_left_time_tv, "距活动开始")
            timer.start(startTime - System.currentTimeMillis())
            timer.setOnCountdownEndListener {
                notifyItemChanged(helper.adapterPosition)
            }
            helper.setVisible(R.id.tv_subscribe_num, true)
            helper.setText(R.id.tv_subscribe_num, "${item.seckillActProductExtDTO.subscribeNum}人已预约")
            if (item.seckillActProductExtDTO.subscribeFlg == 1) {
                button.text = "取消提醒"
                button.setTextColor(ContextCompat.getColor(mContext, R.color.color_999999))
                button.background = ContextCompat.getDrawable(mContext, R.drawable.shape_90_999999_solid_4dp)
                button.setOnClickListener { clickButtonListener?.onClickButton(1, helper.adapterPosition, item.seckillActProductExtDTO.seckillActId) }
            } else {
                button.text = "预约提醒"
                button.setTextColor(ContextCompat.getColor(mContext, R.color.white))
                button.background = ContextCompat.getDrawable(mContext, R.drawable.shape_f54d53_solid_4dp)
                button.setOnClickListener { clickButtonListener?.onClickButton(2, helper.adapterPosition, item.seckillActProductExtDTO.seckillActId) }
            }

        } else if (System.currentTimeMillis() in startTime..endTime!!) {
            progress.visibility = View.VISIBLE
            helper.setText(R.id.tv_seckill_left_time_tv, "时间还剩")
            timer.customTimeShow(endTime - System.currentTimeMillis() >= 1000 * 60 * 60 * 24, true, true, true, false)
            timer.start(endTime - System.currentTimeMillis())
            timer.setOnCountdownEndListener {
                this.remove(helper.adapterPosition)
            }
            helper.setVisible(R.id.tv_subscribe_num, false)
            if (item.seckillActProductExtDTO?.stock != item.seckillActProductExtDTO?.sales) {//没有销售完
                button.text = "抢购"
                button.setTextColor(ContextCompat.getColor(mContext, R.color.white))
                button.background = ContextCompat.getDrawable(mContext, R.drawable.shape_f54d53_solid_4dp)
            } else {
                button.text = "已抢光"
                button.setTextColor(ContextCompat.getColor(mContext, R.color.white))
                button.background = ContextCompat.getDrawable(mContext, R.drawable.shape_50_f54d53_solid_4dp)

            }
            //重置点击事件 打开详情
            button.setOnClickListener {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    val map = HashMap<String, Any>()
                    map[Constants.GOODS_DETAIL_ID] = item.spuId
                    map[Constants.GOODS_SKU_ID] = item.skuId
                    map[Constants.GOODS_DETAIL_SOURCE] = if (showType == "2") "酒窖全部秒杀" else ""
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
                }
            }
        }
        item.seckillActProductExtDTO?.let {
            val actPrice = if (SpUtils.getInstance().isFans) it.fansPrice.toString() else it.price.toString()
            helper.setText(R.id.tv_goods_seckill_price, AmountUtil.changeF2Y(actPrice))
        }
        //划线价
        val tempLinePrice = if (SpUtils.getInstance().isFans) item.fansPrice.toString() else item.price.toString()
        helper.setText(R.id.tv_good_price, "¥" + AmountUtil.changeF2Y(tempLinePrice))

        helper.itemView.setOnClickListener {
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val map = HashMap<String, Any>()
                map[Constants.GOODS_DETAIL_ID] = item.spuId
                map[Constants.GOODS_SKU_ID] = item.skuId
                map[Constants.GOODS_DETAIL_SOURCE] = if (showType == "2") "酒窖全部秒杀" else "平台秒杀专题页"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
            }
        }

    }
}